import React, { useEffect, useState } from 'react';

function Function() {
  console.log('函数被执行');

  const initialTimer = 10;

  const [timer, setTimer] = useState(initialTimer);
  const [hello, setHello] = useState('hi');

  // const [obj, setObj] = useState({

  // });

  useEffect(() => {
    console.log('Effect 被执行');
    // setInterval(() => {
    //   console.log('Timer + 1');
    //   setTimer(oldTimer => oldTimer + 1);
    //   // BAD
    //   // setTimer(timer + 1); // 闭包变量，始终是初始值
    // }, 1000);

    const timer = setTimeout(() => {
      setTimer(timer + 1);
    }, 1000);

    return () => {
      console.log('清理');
      clearTimeout(timer);
    };
  }, [timer]);

  useEffect(() => {
    setHello(hello + ' 我加载好了');
  }, []);

  const onX2 = () => {
    setTimer(timer * 2);
  };

  const onMinus1 = () => {
    setTimer(timer - 1);
  };

  const onReset = () => {
    setTimer(initialTimer);
  };

  return (
    <>
      <button onClick={onX2}>X2</button>
      <button onClick={onMinus1}>-1</button>
      <button onClick={onReset}>Reset</button>
      <h3>{hello}</h3>
      <div>第一个函数组件 {timer}</div>
    </>
  );
}

export default Function;
